<template>
  <div>
    <h3>节流</h3>
    <p>

    </p>

    <h3>防抖</h3>
    <p>
      防抖函数 debounce
      指的是某个函数在某段时间内，无论触发了多少次回调，都只执行最后一次。
    </p>
    <div>{{ count }}</div>
    <input type="text" @keyup="debounce1" />
    <!-- <button @click="debounce(fnn, 3000)()">点击防抖</button> -->
  </div>
</template>

<script lang="ts">
import { defineComponent } from "@vue/composition-api";

let timer: any = null

export default defineComponent({
  setup() {},
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    debounce1() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        console.log("防抖...");
        timer = undefined;
      }, 2000);
    },
    debounce(fn: any, wait = 3000) {
      let timer: any = null;
      return function () {
        // 如果已经设定过定时器就清空上一次的定时器
        if (timer) clearTimeout(timer);
        // 开始设定一个新的定时器，定时器结束后执行传入的函数
        timer = setTimeout(() => {
          fn();
        }, wait);
      };
    },
    fnn() {
      ++this.count;
      console.log("--你在防抖--", this.count, new Date());
    },
  },
});
</script>

<style scoped>
button {
  background-color: #2f54eb;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
}
</style>
